package controller

import (
	"net/http"
	"redisconn/redisclient"
	"utils"
)

func infoHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(`this is info`))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		w.Write([]byte(`{"result":"0000"}`))
	} else if r.Method == "GET" {
		w.WriteHeader(500)
		w.Write([]byte(`{"result":"9999"}`))
	}
}

func redisHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		key := r.FormValue("key")
		if key == "" {
			w.Write([]byte(`{"result":"9998"}`))
			return
		}
		value, err := redisclient.Get(key)
		if err != nil {
			w.Write([]byte(`{"result":"9999"}`))
		} else {
			json := "{\"result\":\"0000\",\"value\":\"" + value + "\"}"
			w.Write([]byte(json))
		}
	} else if r.Method == "GET" {
		key := r.FormValue("key")
		value := r.FormValue("value")
		err := redisclient.Set(key, value)
		if err != nil {
			w.Write([]byte(`{"result":"0000"}`))
		} else {
			w.Write([]byte(`{"result":"9999"}`))
		}

	}
}

func Controller() {
	mux := http.NewServeMux()

	// info
	mux.HandleFunc("/info", infoHandler)
	// interface
	mux.HandleFunc("/hello", helloHandler)
	// redis
	mux.HandleFunc("/redis", redisHandler)

	err := http.ListenAndServe(":8088", mux)
	utils.Check(err)
}
